package controller

import (
	"github.com/gin-gonic/gin"
	"github.com/samber/lo"
	"k9-panel/app/adapter/internal"
	"k9-panel/app/adapter/internal/convert"
	"k9-panel/app/model"
	"k9-panel/app/response"
	"k9-panel/app/service"
	"k9-panel/app/service/dto"
	"net/http"
)

var (
	Project *ProjectController
)

func init() {
	Project = new(ProjectController)
	Project.List = Project.list
}

type ProjectController struct {
	common
	List gin.HandlerFunc
}

func (t *ProjectController) list(c *gin.Context) {
	var (
		projectReq internal.ProjectListRequest
	)

	err := c.BindQuery(&projectReq)
	if err != nil {
		panic(err)
	}
	user, err := t.GetLoginUser(c)
	if err != nil {
		panic(err)
	}
	//
	ps, err := service.Project.QueryList(&dto.ProjectListParam{
		Account: user.ToAccount(),
	})
	if err != nil {
		panic(err)
	}
	list := lo.Map(ps, func(item *model.Project, _ int) *internal.ProjectRsp {
		return convert.ProjectModel2ProjectRsp(item)
	})
	c.JSON(http.StatusOK, response.Success(list))
	return

}

func (t *ProjectController) Add(c *gin.Context) {
	var (
		project    model.Project
		projectAdd internal.ProjectAdd
	)
	err := c.BindJSON(&projectAdd)
	if err != nil {
		panic(err)
	}
	project.Name = projectAdd.Name
	project.Description = projectAdd.Description
	if projectAdd.EnvironmentId > 0 {

		get, err := service.Environment.Get(uint(projectAdd.EnvironmentId))
		if err != nil {
			panic(err)
		}
		project.Environments = []model.Environment{*get}
	}
	id, err := service.Project.Create(&project)
	if err != nil {
		panic(err)
	}
	c.JSON(http.StatusOK, response.Success(id))
	return
}
func (t *ProjectController) Delete(c *gin.Context) {
	var (
		project model.Project
	)
	err := c.BindJSON(&project)
	if err != nil {
		panic(err)
	}
	id, err := service.Project.Delete(&project)
	if err != nil {
		panic(err)
	}
	c.JSON(http.StatusOK, response.Success(id))
	return
}
func (t *ProjectController) Update(c *gin.Context) {
	var (
		project model.Project
	)
	err := c.BindJSON(&project)
	if err != nil {
		panic(err)
	}
	id, err := service.Project.Update(&project)
	if err != nil {
		panic(err)
	}
	c.JSON(http.StatusOK, response.Success(id))
	return
}
